﻿using System;
using System.Linq;

namespace CoreShop.Library.Units
{
    public class BarcodeChecker
    {
        /// <summary>
        /// 计算EAN-13校验码
        /// </summary>
        /// <param name="barcode">前12位条码</param>
        /// <returns>完整的13位条码</returns>
        public static string CalculateEAN13CheckDigit(string barcode)
        {
            if (string.IsNullOrEmpty(barcode))
                throw new ArgumentNullException(nameof(barcode));

            if (barcode.Length != 12)
                throw new ArgumentException("EAN-13条码必须是12位数字", nameof(barcode));

            if (!barcode.All(char.IsDigit))
                throw new ArgumentException("条码必须包含数字", nameof(barcode));

            int sum = 0;

            // 计算奇数位和偶数位的和
            for (int i = 0; i < 12; i++)
            {
                int digit = barcode[i] - '0';

                // 奇数位(从右数)乘以3，偶数位乘以1
                if ((i + 1) % 2 == 0)
                {
                    sum += digit * 3;
                }
                else
                {
                    sum += digit;
                }
            }

            // 计算校验码
            int checkDigit = (10 - (sum % 10)) % 10;

            return barcode + checkDigit;
        }

        /// <summary>
        /// 验证EAN-13条码的校验码
        /// </summary>
        public static bool ValidateEAN13(string barcode)
        {
            if (string.IsNullOrEmpty(barcode) || barcode.Length != 13)
                return false;

            if (!barcode.All(char.IsDigit))
                return false;

            string baseCode = barcode.Substring(0, 12);
            string calculatedCode = CalculateEAN13CheckDigit(baseCode);

            return barcode == calculatedCode;
        }
    }
}
